package com.example.springbootjackson.traceId;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 不建议使用拦截器,建议用aop拿到入参和出参
 */
@Component
public class TestTraceInterceptor extends HandlerInterceptorAdapter {

    public static final String TRACE_ID = "TRACE_ID";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //自身内部MDC
        MDC.put(TRACE_ID, traceId(request));
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        MDC.clear();
    }


    public static String traceId(HttpServletRequest request) {
        String traceId = request.getHeader(TRACE_ID);
        if (!StringUtils.isEmpty(traceId)) {
            return traceId;
        }
        return UUID.randomUUID().toString().toUpperCase();
    }
}
